<?php
class NoBusinessBase_Helper_SortAndRangeExtraction
{
   public static function fetch(Zend_Controller_Request_Abstract $pRequest, $defaultSortName)
   {
      // Get range
      $range = $pRequest->getHeader('Range', 'items=0-9999999');

      // Get sort
      $sort = $pRequest->getHeader('sortBy', false);
      if(!$sort)
         $sort = $pRequest->getParam('sortBy', '-Id');

      $rangeParams = NoBusinessBase_Helper_SortAndRangeExtraction::fixRange($range);
      $sortParams = NoBusinessBase_Helper_SortAndRangeExtraction::fixSort($sort, $defaultSortName);
      return array_merge($rangeParams, $sortParams);
   }

   public static function fixRange($range)
   {
      // extract range
      $start = null;
      $limit = null;
      if($range !== false)
      {
         $range = substr($range, 6);
         $rangeParts = explode('-', $range);
         $start = $rangeParts[0];
         $limit = $rangeParts[1] - $rangeParts[0] + 1;
      }
      
      if(!$start)
         $start = 0;

      return array('start' => $start, 'limit' => $limit);
   }


   public static function fixSort($sort, $defaultSortName)
   {
      $sortArray = explode(',', $sort);
      if(!is_array($sortArray) || count($sortArray) === 0)
         return array('sort' => array($defaultSortName . ' Desc'));

      $sortFixed = array();
      foreach($sortArray as $sort)
      {
         if($sort === '')
         {
            $sortFixed = array($defaultSortName . ' Desc');
            break;
         }
         $order = 'Asc';
         if(strchr($sort,'-'))
         {
            $sort = substr($sort,1,strlen($sort));
            $order = 'Desc';
         }
         $sort = trim($sort);
         $sortFixed[] = $sort . ' ' . $order;
      }

      return array('sort' => $sortFixed);
   }
}
